﻿using AspNetCoreWebApiRoute.Module;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace AspNetCoreWebApiRoute.ModelBinder
{
    public class CookieModerBinder : IModelBinder
    {
        public  Task BindModelAsync(ModelBindingContext bindingContext)
        {
            Type type = bindingContext.ModelType;
            var Cookies = bindingContext.HttpContext.Request.Cookies;
            // 2、判断是否是用户类型
            if (type.Equals(typeof(User)))
            {
                // 3、开始绑定
                // 3.1、赋值
                User user = new User();
                user.Id = int.Parse(Cookies["Id"]);
                user.Name = Cookies["Name"];

                // 3.2、绑定 (Action 用户参数赋值)
                bindingContext.Result = ModelBindingResult.Success(user);
            }
            return Task.CompletedTask;
        }
    }
}
